from flask import Blueprint, request, jsonify
from models import Website, Image
from extensions import db
from utils.download import download_image
import re
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.response import success_response,error_response

api = Blueprint('website_api', __name__)


@api.route('/', methods=['GET'])
@jwt_required()
def get_websites():
    page = request.args.get('page', default=1, type=int)
    limit = request.args.get('limit', default=10, type=int)

    query = Website.query.order_by(Website.id)
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    for w in pagination.items:
        a = w.to_dict()
        print(a)
    return jsonify({
        "code": 0,
        "msg": "查询成功",
        "page": page,
        "limit": limit,
        "count": pagination.total,
        "data": [w.to_dict() for w in pagination.items]
    })


@api.route('/add', methods=['POST'])
@jwt_required()
def add_website():
    data = request.form
    name = data.get('name', '').strip()
    url = data.get('url', '').strip()
    description = data.get('description', '').strip()
    logo = data.get('logo', '').strip()
    cat_id = data.get('category_id')

    if not (name and url and cat_id):
        return jsonify(error_response('参数错误', 400)), 400
    if not re.match(r'^https?://', url):
        url = 'http://' + url
    if Website.query.filter_by(url=url).first():
        return jsonify(error_response('网址{url}已存在', 409, f'')), 400

    local_logo = download_image(logo, ip=request.remote_addr)
    site = Website(name=name, url=url, description=description, logo=logo, local_logo=local_logo, category_id=cat_id)
    db.session.add(site)
    db.session.commit()
    return jsonify(success_response(msg='添加成功', data=site.to_dict()))


@api.route('/<int:website_id>', methods=['DELETE'])

def delete_website(website_id):
    site = Website.query.get_or_404(website_id)
    db.session.delete(site)
    db.session.commit()
    return jsonify({'message': '删除成功'})

@api.route('/<int:website_id>', methods=['PUT'])

def update_website(website_id):
    site = Website.query.get_or_404(website_id)
    data = request.get_json()

    name = data.get('name', '').strip()
    url = data.get('url', '').strip()
    description = data.get('description', '').strip()
    logo = data.get('logo', '').strip()
    cat_id = data.get('category_id')

    if not (name and url and cat_id):
        return jsonify(error_response('参数错误', 400)), 400

    if not re.match(r'^https?://', url):
        url = 'http://' + url

    exists = Website.query.filter(Website.url == url, Website.id != website_id).first()
    if exists:
        return jsonify(error_response('error', 409, '该网址已存在')), 409

    img = Image.query.filter_by(source_url=logo).first()
    if site.local_logo is None or img is None:
        site.local_logo = download_image(logo, ip=request.remote_addr)

    site.name = name
    site.url = url
    site.description = description
    site.logo = logo
    site.category_id = cat_id
    db.session.commit()
    return jsonify(success_response(msg='网站更新成功'))

